package main

/// https://systembash.com/a-simple-go-tcp-server-and-tcp-client/
// this go exec file is for test purpose, will act as GPRS model in IFMS

import (
	"fmt"
	"log"
	"os"
	"regexp"
	// "os"

	"time"
)

const (
	MAXDEVCT = 64 //1024 // 240 // max 99999

	MsgInterval = 15 //*time.Second //  wait 30 second before send next msg to TCP server

	SlaSeconds = 7 //*time.MilliSecond  // if deply time reach this porint, then we stop load test.
)

var logger *log.Logger
var DevNamePrefix string

type InstancePorf struct {
	sendCount int64
	elapsed   float64 //time.Duration
}

type Prof struct {
	device_ct int64
	sendCouts int64
	elapsed   float64 //time.Duration
	avg_sla   float64 // time.Duration
}

func (p *Prof) avgSla() float64 {

	return p.avg_sla
}

func main() {
	// var text string
	remoteIp := "120.76.151.52"
	remotePort := os.Getenv("TPRT")
	DevNamePrefix = "LDTST"

	if len(os.Args) > 1 && (os.Args[1] == "localhost" || regexp.MustCompile(`^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$`).MatchString(os.Args[1])) {
		remoteIp = os.Args[1]
	}

	if len(os.Args) > 2 && regexp.MustCompile(`^[0-9]{2,4}$`).MatchString(os.Args[2]) {
		remotePort = os.Args[2]
	}

	if len(os.Args) > 3 && regexp.MustCompile(`^[A-Z]{5}$`).MatchString(os.Args[3]) {
		DevNamePrefix = os.Args[3]
	}

	remoteAddr := remoteIp + remotePort
	// loopFlag := true
	// svrEcho := true

	var devices []*Device

	logger = log.New(os.Stdout, "LoadTest>", log.LstdFlags|log.Lshortfile)

	stat := make(chan InstancePorf)
	qflag := make(chan bool)

	prof := &Prof{device_ct: 0,
		elapsed: 0,
	}

	fmt.Printf(" Remote Addr: %s \n", remoteAddr)
	fmt.Println("go func for svg elapsed calculation")
	fmt.Printf("go func for new device loop, start at  prof.device_ct = %v \n ", prof.device_ct)

	go func() {
		fmt.Println("go func for svg elapsed calculation")
		for {
			s := <-stat
			prof.sendCouts += s.sendCount
			prof.elapsed += s.elapsed
			prof.avg_sla = prof.elapsed / float64(prof.sendCouts)
			fmt.Printf("===Device Ct: %v    Send_ct: %v     Avg_sla : %v\n",
				prof.device_ct, prof.sendCouts, prof.avg_sla)

			if prof.avg_sla > SlaSeconds {

				for _, d := range devices {
					d.quiting <- true
				}
				logger.Printf(" Avg sla (%v) > SlaSeocnds(%v), quit..... \n", prof.avg_sla, SlaSeconds)
				qflag <- true

				return

			}

		}

	}()

	// go func() {

	fmt.Printf("go func for new device loop, start at  prof.device_ct = %v \n ", prof.device_ct)
	for prof.device_ct <= MAXDEVCT {

		d := newDevice(remoteAddr, stat)
		if d != nil {

			devices = append(devices, d)

			prof.device_ct++

		}

		time.Sleep(time.Second)
	}

	// }()
	<-qflag
}
